package com.hunliji.monitor.share.component.db.impl;

import com.alibaba.fastjson.JSON;
import com.hunliji.common.exception.WarnException;
import com.hunliji.monitor.share.component.ComponentLocator;
import com.hunliji.monitor.share.component.db.DatabaseConnectionsAdapter;
import com.hunliji.monitor.share.component.db.DbHandlerFacade;
import com.hunliji.monitor.share.component.db.model.DatabaseConnectProperty;
import com.hunliji.monitor.share.component.db.model.SqlCheckResult;
import com.hunliji.monitor.share.enums.db.SqlCheckStatusEnum;
import com.hunliji.monitor.share.utils.SqlParseUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;

/**
 * db 方法
 * @author wuchen
 */
@Service
public class DbHandlerFacadeImpl implements DbHandlerFacade {
    private static final Logger logger = LoggerFactory.getLogger(DbHandlerFacadeImpl.class);
    public static final String SPLIT_CHAR_SQL = ";";
    @Override
    public SqlCheckResult checkDDL(String sql) {
        //1 语法校验
        try {
            Integer checkStatus = SqlParseUtils.checkDDL(sql);
            return SqlCheckResult.build(checkStatus,null);
        }catch (WarnException e){
            return SqlCheckResult.build(SqlCheckStatusEnum.UNENFORCEABLE.getCode(),e.getMsg());
        }
    }

    @Override
    public void executeSql(String sql,String host,String tableName,String username,String password) {
        Integer checkStatus = SqlParseUtils.checkDDL(sql);
        if(!SqlCheckStatusEnum.EXECUTABLE.getCode().equals(checkStatus)){
            throw new WarnException("当前sql不可执行");
        }
        DatabaseConnectProperty property = DatabaseConnectProperty.build(
                host, tableName,username, ComponentLocator.getAppConfig().getSecretKey(),password);

        for (String sqlExecute : sql.split(SPLIT_CHAR_SQL)) {
            if (StringUtils.isNotBlank(sqlExecute)) {
                DatabaseConnectionsAdapter.execute(property, sqlExecute);
            }
        }
    }

    @Override
    public void executeQuerySql(String sql, String host, String tableName, String username, String password) {
//        Integer checkStatus = SqlParseUtils.checkDDL(sql);
//        if(!SqlCheckStatusEnum.EXECUTABLE.getCode().equals(checkStatus)){
//            throw new WarnException("当前sql不可执行");
//        }
        DatabaseConnectProperty property = DatabaseConnectProperty.build(
                host, tableName,username, ComponentLocator.getAppConfig().getSecretKey(),password);
        ResultSet resultSet = null;
        for (String sqlExecute : sql.split(SPLIT_CHAR_SQL)) {
            if (StringUtils.isNotBlank(sqlExecute)) {
                resultSet = DatabaseConnectionsAdapter.executeQuery(property, sqlExecute);
                break;
            }
        }
        logger.info("查询到到数据：{}", JSON.toJSONString(resultSet));
    }
}
